import os,openpyxl
import requests
import json


class Spider_shop(object):
    # 初始信息
    def __init__(self, url01):
        self.url = url01
        self.shop_name = ''
        self.headers = {
            'user-agent': 'Mozilla/5.0 (Linux; Android 12; V2055A Build/SP1A.210812.003; wv) AppleWebKit/537.36 (KHTML, like G'
                          'ecko) Version/4.0 Chrome/86.0.4240.99 XWEB/4317 MMWEBSDK/20220903 Mobile Safai/537.36 MMWEB'
                          'ID/396 MicroMessenger/8.0.28.2240(0x281C3F) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI'
                          '/arm64 MiniProgramEnv/android',
            'host': 'api.app.52czxy.com',
            'accept-encoding': 'gzip',
        }

    def get_shopInfo(self):
        self.shop_r = requests.get(url=self.url, headers=self.headers)

        json_shop = json.loads(self.shop_r.text)

        self.shop_name = json_shop.get("data").get('shopName')
        if '/' in self.shop_name:
            self.shop_name = self.shop_name.replace('/', ',')
        elif '\\' in self.shop_name:
            self.shop_name = self.shop_name.replace('\\', ',')
        elif '➕' in self.shop_name:
            self.shop_name = self.shop_name.replace('➕', ',')

        if not os.path.exists('/Users/x/Desktop/getcontent/%s' % self.shop_name):
            print('获取的店铺名称为：', self.shop_name)
            os.mkdir('/Users/x/Desktop/getcontent/%s' % self.shop_name)
            self.get_shop_class()
        else:
            print('店铺信息已存在，程序结束')
            return
    def get_shop_class(self):
        class_url = self.url + '/goods/category/list'
        class_r = requests.get(url=class_url, headers=self.headers)

        json_content = json.loads(class_r.text)
        class_list = json_content.get("data")
        self.workxsl = openpyxl.Workbook()

        for index, i in enumerate(class_list):
            class_id = i.get('id')
            class_name = i.get('name')
            if '/' in class_name:
                class_name = class_name.replace('/', ',')
            elif '\\' in class_name:
                class_name = class_name.replace('\\', ',')
            elif '➕' in self.shop_name:
                class_name = class_name.replace('➕', ',')
            print('ClassiFication`ing----------', class_name)

            self.write_excel(index, class_id, class_name)
    def write_excel(self, index, class_id, class_name):

        goods_url = self.url + '/goods/category/%s/goods/list' % class_id
        goods_r = requests.get(url=goods_url, headers=self.headers)
        json_content = json.loads(goods_r.text)
        goods_list = json_content.get("data")
        self.workxsl.create_sheet(index=index, title=class_name)
        worksheet = self.workxsl.worksheets[index]
        worksheet.cell(1, 1, '商品名')
        worksheet.cell(1, 2, '定价')
        worksheet.cell(1, 3, '现价')
        for i, goods in enumerate(goods_list.get("goodsList")):
            goods_name = goods.get('name')
            goods_Price = goods.get('unitPrice')
            new_goods_Price = goods.get('discountPrice')

            img_URL = goods.get('imageUrl')

            worksheet.cell(i + 2, 1, goods_name)
            worksheet.cell(i + 2, 2, goods_Price)

            if new_goods_Price == None:
                worksheet.cell(i + 2, 3, goods_Price)
            else:
                from openpyxl.styles import Font, PatternFill, Border, Side, Alignment
                font = Font(name='微软雅黑', size=10, bold=False, italic=False, vertAlign=None,
                            underline='none', strike=False, color='e53e31')
                worksheet.cell(i + 2, 3, new_goods_Price).font = font

            if '/' in goods_name:
                goods_name = goods_name.replace('/', ',')
            elif '\\' in goods_name:
                goods_name = goods_name.replace('\\', ',')

            with open('/Users/x/Desktop/getcontent/%s/%s.png' % (self.shop_name, goods_name), 'wb') as f:

                headers = {
                    'user-agent': 'Mozilla/5.0 (Linux; Android 12; V205A Build/SP1A.210812.003; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/86.0.4240.99 XWEB/4317 MMWEBSDK/20220903 Mobile Safari/537.36 MMWEBID/396 MicroMessenger/8.0.28.2240(02801C3F) WeChat/arm4 Weixin NetType/WIFI Language/zh_CN ABI/arm6 MiniProgramEnv/android'
                }

                img_content = requests.get(url=img_URL, headers=headers)
                if img_content:
                    f.write(img_content.content)
                    print("Write this commodity", goods_name)

            self.workxsl.save('/Users/x/Desktop/getcontent/%s/%s.xls' % (self.shop_name, self.shop_name))


if __name__ == '__main__':
    # try:
    in_url = input('StorePathID：')
    spider = Spider_shop(in_url)
    spider.get_shopInfo()